package com.exercises;

import com.alibaba.fastjson.JSONObject;

import java.util.Arrays;
import java.util.Comparator;
import java.util.PriorityQueue;

class ExerciseSmallestK {
    public static void main(String[] args) {
        System.out.println(JSONObject.toJSONString(smallestK(new int[]{1, 3, 5, 7, 2, 4, 6, 8}, 4)));
    }

    public static int[] smallestK(int[] arr, int k) {
        int n = arr.length;
        if (k > n) return arr;
        if (k == 0) return new int[]{};

        PriorityQueue<Integer> queue = new PriorityQueue<Integer>(new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o2 - o1;
            }
        });
        for (int i = 0; i < k; i++) {
            queue.offer(arr[i]);
        }
        for (int i = k; i < n; i++) {
            int value = arr[i];
            if (queue.peek() > value) {
                queue.poll();
                queue.offer(value);
            }
        }

        int[] result = new int[k];
        int i = 0;
        while (!queue.isEmpty()) {
            result[i++] = queue.poll();
        }
        return result;
    }


}

